import {
  PlusOutlined,
  VideoCameraOutlined,
  PictureOutlined,
  StarOutlined,
  ManOutlined,
  WomanOutlined,
} from "@ant-design/icons";
import { DrawerForm } from "@ant-design/pro-components";
import {
  Avatar,
  Button,
  Card,
  Form,
  message,
  Image,
  List,
  Tabs,
  Progress,
  Divider,
  Descriptions,
  Tag,
  Checkbox,
} from "antd";
import { useEffect, useState, useRef } from "react";
import type { TabsProps } from "antd";
import CompilationCreator from "./CompilationCreatorForm";
import { getHistoryFolderFaceGroup } from "@/services/api/api-intelligent-processing";
import ImageViewer from "@/components/ImageViewr";
import VideoViewer from "@/components/VideoView";

interface FaceDetailProps {
  folderId: number;
  record: ProcessingData.listRecord;
  onRefurbish: () => void;
  selected?: boolean;
  onSelectChange?: (selected: boolean) => void;
}

const FaceDetail: React.FC<FaceDetailProps> = ({
  onRefurbish,
  record,
  folderId,
  selected = false,
  onSelectChange,
}) => {
  const [form] = Form.useForm();
  const [detailData, setDetailData] =
    useState<ProcessingData.detailRecord | null>(null);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState("1");
  const [showCompilationCreator, setShowCompilationCreator] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);

  const loadDetailData = async () => {
    setLoading(true);
    try {
      const response = await getHistoryFolderFaceGroup({
        folderId,
        faceGroupId: record.face_group_id,
      });
      setDetailData(response.data);
    } catch (error) {
      message.error("加载详情失败");
    } finally {
      setLoading(false);
    }
  };

  const handleCreateCompilation = () => {
    // 创建集锦的逻辑
    message.success("集锦创建成功");
    setShowCompilationCreator(false);
  };

  const handleCheckboxChange = (e: any) => {
    e.stopPropagation(); // 阻止事件冒泡
    if (onSelectChange) {
      onSelectChange(e.target.checked);
    }
  };

  const items: TabsProps["items"] = [
    {
      key: "1",
      label: (
        <span>
          <PictureOutlined />
          原始图片
        </span>
      ),
      children: (
        <div style={{ marginBottom: 24 }}>
          {detailData?.original_images?.length > 0 ? (
            <List
              grid={{ gutter: 16, column: 2 }}
              dataSource={detailData?.original_images}
              renderItem={(image, index) => (
                <List.Item>
                  <Card
                    size="small"
                    title={`原始图片 ${index + 1}`}
                    extra={
                      image.position && <Tag color="blue">已检测到人脸</Tag>
                    }
                  >
                    <ImageViewer
                      imageUrl={image.url}
                      position={image.positions[0]}
                      similarity={image.similarity}
                    />
                  </Card>
                </List.Item>
              )}
            />
          ) : (
            <div style={{ textAlign: "center", padding: 24 }}>
              <p>暂无原始图片</p>
            </div>
          )}
        </div>
      ),
    },
    {
      key: "2",
      label: (
        <span>
          <VideoCameraOutlined />
          视频片段
        </span>
      ),
      children: (
        <div style={{ marginBottom: 24 }}>
          {detailData?.video_clips?.length > 0 ? (
            <List
              grid={{ gutter: 16, column: 1 }}
              dataSource={detailData?.video_clips}
              renderItem={(clip, index) => {
                const clipDuration =
                  clip.end_time && clip.start_time
                    ? clip.end_time - clip.start_time
                    : undefined;

                return (
                  <List.Item>
                    <Card
                      title={`视频片段 ${index + 1}`}
                      extra={
                        <span>
                          时长:{" "}
                          {clipDuration ? clipDuration.toFixed(1) + "s" : "N/A"}
                        </span>
                      }
                    >
                      <VideoViewer
                        videoUrl={clip.clip_url}
                        positions={clip.positions}
                        startTime={clip.start_time}
                        endTime={clip.end_time}
                        clipDuration={clipDuration}
                        style={{ maxWidth: "100%" }}
                      />
                    </Card>
                  </List.Item>
                );
              }}
            />
          ) : (
            <div style={{ textAlign: "center", padding: 24 }}>
              <p>暂无视频片段</p>
            </div>
          )}
        </div>
      ),
    },
    {
      key: "3",
      label: (
        <span>
          <VideoCameraOutlined />
          集锦
        </span>
      ),
      children: (
        <div style={{ marginBottom: 24 }}>
          {detailData?.highlights?.length > 0 ? (
            <List
              grid={{ gutter: 16, column: 2 }}
              dataSource={detailData.highlights}
              renderItem={(clip, index) => (
                <List.Item>
                  <Card
                    title={`集锦片段 ${index + 1}`}
                    extra={<span>{clip?.created_at}</span>}
                  >
                    <video
                      ref={videoRef}
                      width="100%"
                      style={{ maxHeight: 300 }}
                      controls
                      src={clip?.highlight_url ?? ""}
                    />
                  </Card>
                </List.Item>
              )}
            />
          ) : (
            <div style={{ textAlign: "center", padding: 24 }}>
              <p>暂无集锦片段</p>
            </div>
          )}
        </div>
      ),
    },
  ];

  const handleDrawerOpen = (open: boolean) => {
    setDrawerVisible(open);
    if (open) {
      loadDetailData();
    } else {
      setDetailData(null);
      setActiveTab("1");
    }
  };

  return (
    <>
      <Card
        hoverable
        title={record.name}
        style={{ height: 170 }}
        cover={
          <Avatar
            src={record.thumbnail_url}
            size="large"
            style={{
              height: 120,
              width: "100%",
              objectFit: "cover",
              marginTop: -20,
            }}
          />
        }
        onClick={() => setDrawerVisible(true)}
        extra={
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              gap: "6px",
              margin: "-20px 0px",
            }}
          >
            <span
              style={{
                fontSize: "13px",
                lineHeight: "1.2",
                flex: 1,
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              }}
            >
              分组ID：{record.face_group_id}
            </span>
            <Checkbox
              checked={selected}
              onChange={handleCheckboxChange}
              onClick={(e) => e.stopPropagation()}
            />
          </div>
        }
      ></Card>

      <DrawerForm
        title={`人脸详情 - ${record.face_group_id}`}
        resize={{ maxWidth: window.innerWidth * 0.8, minWidth: 800 }}
        form={form}
        open={drawerVisible}
        onOpenChange={handleDrawerOpen}
        autoFocusFirstInput
        drawerProps={{ destroyOnClose: true }}
        submitter={false}
      >
        {loading ? (
          <div style={{ textAlign: "center", padding: 24 }}>
            <Progress type="circle" percent={50} />
            <p>加载中...</p>
          </div>
        ) : detailData ? (
          <>
            <div style={{ textAlign: "center", marginBottom: 16 }}>
              <Avatar src={record.thumbnail_url} size={120} />
              <div>分组ID: {detailData.face_group_id}</div>
            </div>
            <Tabs activeKey={activeTab} items={items} onChange={setActiveTab} />
            <Divider />
          </>
        ) : (
          <div>数据加载失败</div>
        )}
      </DrawerForm>
    </>
  );
};

export default FaceDetail;
